﻿// ***********************************************************************
// 项目名称         : 新疆嘉潤
// 程序名称         : SbdaController.cs
// 功能说明         ：设备档案管理管理器 实现设备管理的增加、删除、修改、查询等功能
// 编 写 人         : Xiaoping
// 创建日期         : 07-25-2014
// 软件版权         : 经纬科技
// ***********************************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Http;
using Jw.Models;
using Jw.Core;
using Jw.Web.Areas.Dev.Common;
using Newtonsoft.Json.Linq;
using Jw.Web.App_Start;

namespace Jw.Web.Areas.Dev.Controllers
{
    public class SbdaController : BaseController
    {
        //
        // GET: /Dev/Sbda/
        /// <summary>
        /// 设备管理查询列表页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            var codeService = new sys_codeService();
            var model = new
            {
                idField = "Sbda_Sbbm", //主键
                urls = DevHelper.GetIndexUrls("Sbda"),
                resx = DevHelper.GetIndexResx("设备档案"),
                dataSource = new
                {
                    sbztItems = codeService.GetTextListByType("Sbzt"),//设备状态
                    monthItems = codeService.GetMonthItems()
                },
                form = new
                {
                    Sbda_Sbbm = "",//设备编码
                    Sbda_Sbmc = "",
                    Sbda_Sydwbh = "",//使用单位编号
                    Sbda_Sbcs = "",//生产长商
                    Sbda_Sbzt = ""//设备状态
                }

            };
            return View(model);
        }

        /// <summary>
        /// 设备管理编辑明细页面(多tabs页进行编辑)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [System.Web.Http.HttpGet]
        [MvcMenuFilter(false)]
        public ActionResult Edit(string id = "")
        {
            string[] arg = id.Split(';'); // 编号  +";" + 类别编号
            string sLbbh = "";
            id = arg[0];
            if (arg.Length == 2)
            {
                id = arg[0];
                sLbbh = arg[1];
            }
            var userName = DevHelper.GetUserName();
            var codeService = new sys_codeService();

            var model = new
            {
                urls = new
                {
                    getdata = "/api/Dev/Sbda/GetPageData/",        //获取主表数据及数据滚动数据api
                    edit = "/api/Dev/Sbda/edit/",                      //数据保存api
                    audit = "/api/Dev/Sbda/audit/",                    //审核api
                    newkey = "/api/Dev/Sbda/GetNewRowId/"            //获取新的明细数据的主键(日语叫采番)
                },
                resx = new
                {
                    rejected = "已撤消修改！",
                    editSuccess = "保存成功！",
                    auditPassed = "单据已通过审核！",
                    auditReject = "单据已取消审核！"
                },
                dataSource = new
                {
                    pageData = new SbdaApiController().GetPageData(id),
                    sbztItems = codeService.GetTextListByType("Sbzt")
                },
                form = new
                {
                    //设备编号 为最新的ID
                    defaults = new b_Sbda().Extend(new { Sbda_Sbbm = id, Sbda_lbbh = sLbbh, Sbda_Sbzt = "在库", Sbda_Sjly = "手工录入" }),
                    primaryKeys = new string[] { "Sbda_Sbbm" }
                },
                tabs = new object[]{
                    new{
                        //关键部位
                      type = "grid",
                      rowId = "Gjbw_Bwbh",
                      relationId = "Gjbw_Sbbh",
                      defaults = new {Gjbw_Bwbh = "",Gjbw_Bwmc = "部件1",Gjbw_Bwms = "描述",CreatePerson = "",CreateDate = ""},
                      postFields = new string[] { "Gjbw_Bwbh","Gjbw_Bwmc","Gjbw_Bwms","Gjbw_Sbbh","Gjbw_Djbz","Gjbw_Bybz","Gjbw_Yhbz","Gjbw_Remark"}
                    },    
                    new{
                        //技术参数
                      type = "grid",
                      rowId = "Jscs_Csbh",
                      relationId = "Jscs_Sbbh",
                      defaults = new {Jscs_Csbh = "",Jscs_Csmc = "参数1"},
                      postFields = new string[] { "Jscs_Csbh","Jscs_Sbbh","Jscs_Csmc","Jscs_Csms","Jscs_Bzz","Jscs_Sxz","Jscs_Xxz"}
                    },
                    new {
                        //附属设备
                      type = "grid",
                      rowId = "Fssb_Fssbbh",
                      relationId = "Fssb_Sbbh",
                      defaults = new {Fssb_Fssbbh = "",Fssb_Fssbmc = "附属1",Fssb_Sl = 1,Fssb_Yz =0},
                      postFields = new string[] { "Fssb_Sbbh","Fssb_Fssbbh","Fssb_Fssbmc","Fssb_Ggxh","Fssb_Zzcj","Fssb_Jldw","Fssb_Sl","Fssb_Yz","Fssb_Remark"}
                    }
                }
            };

            return View(model);
        }
    }
    /// <summary>
    /// Api
    /// </summary>
    public class SbdaApiController : ApiController
    {
        //todo 改成支持多个Tab
        // 地址：GET api/mms/@(controller)/getnewrowid 预取得新的明细表的行号
        public string GetNewRowId(string type, string key, int qty = 1)
        {
            switch (type)
            {
                case "grid0":
                    //关键部位
                    var service0 = new b_Sbda_GjbwService();
                    return service0.GetNewKey("Gjbw_Bwbh", "maxplus", qty, ParamQuery.Instance().AndWhere("Gjbw_Sbbh", key, Cp.Equal));
                case "grid1":
                    //技术参数
                    var service1 = new b_Sbda_JscsService();
                    return service1.GetNewKey("Jscs_Csbh", "maxplus", qty, ParamQuery.Instance().AndWhere("Jscs_Sbbh", key, Cp.Equal));
                case "grid2":
                    //附属设备
                    var service2 = new b_Sbda_FssbService();
                    return service2.GetNewKey("Fssb_Fssbbh", "maxplus", qty, ParamQuery.Instance().AndWhere("Fssb_Sbbh", key, Cp.Equal));
                default:
                    return "";
            }
        }
        [System.Web.Http.HttpGet]
        public dynamic GetPageData(string id)
        {
            var masterService = new b_SbdaService();
            var pQuery = ParamQuery.Instance().AndWhere("Sbda_Sbbm", id);

            var result = new
            {
                //主表数据
                form = masterService.GetDynamic(pQuery),
                scrollKeys = masterService.ScrollKeys("Sbda_Sbbm", id),
                //明细数据 
                //关键部位
                tab0 = new b_Sbda_GjbwService().GetDynamicList(ParamQuery.Instance().AndWhere("Gjbw_Sbbh", id)),
                //技术参数
                tab1 = new b_Sbda_JscsService().GetDynamicList(ParamQuery.Instance().AndWhere("Jscs_Sbbh", id)),
                //附属设备
                tab2 = new b_Sbda_FssbService().GetDynamicList(ParamQuery.Instance().AndWhere("Fssb_Sbbh", id))
            };
            return result;
        }
        /// <summary>
        /// 得到设备的最新编号
        /// </summary>
        /// <returns></returns>
        public string getnewbillno()
        {
            return new b_SbdaService().GetNewKey("Sbda_Sbbm", "maxplus");
        }
        /// <summary>
        /// 获取设备档案的编号(系统规定档案编号根据父编号规则 如01 0101)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string getnewcode(string id)
        {
            return new b_SbdaService().GetNewCode("Sbda_Sbbm", "Sbda_lbbh", id);
        }

        public dynamic Get(RequestWrapper query)
        {
            query.LoadSettingXmlString(@"
            <settings defaultOrderBy='Sbda_Sbbm DESC'>
            <select>*</select>
                <from>b_Sbda</from>
                    <where defaultForAll='true' defaultCp='equal' defaultIgnoreEmpty='true' >
                        <field name='Sbda_Sbbm'     cp='like'></field>
                        <field name='CreateDate' cp='daterange'></field>
                    </where>
            </settings>");
            var service = new b_SbdaService();
            var pQuery = query.ToParamQuery();
            var result = service.GetDynamicListWithPaging(pQuery);

            return result;
        }
        public void Edit(dynamic data)
        {
            //form 表单
            var formWrapper = RequestWrapper.Instance().LoadSettingXmlString(@"
          <settings>
                <table>
                    b_Sbda
                </table>
                <where>
                    <field name='Sbda_Sbbm' cp='equal'></field>
                </where>
            </settings>");
            var tabsWrapper = new List<RequestWrapper>();
            //关键部位
            tabsWrapper.Add(RequestWrapper.Instance().LoadSettingXmlString(@"
            <settings>
                <table>
                    b_Sbda_Gjbw
                </table>
                <where>
                    <field name='Gjbw_Sbbh' cp='equal'></field>
                    <field name='Gjbw_Bwbh'  cp='equal'></field>
                </where>
            </settings>"));
            //技术参数
            tabsWrapper.Add(RequestWrapper.Instance().LoadSettingXmlString(@"
            <settings>
                <table>b_Sbda_Jscs</table>
                <where>
                    <field name='Jscs_Sbbh' cp='equal'></field>
                    <field name='Jscs_Csbh' cp='equal'></field>
                </where>
            </settings>"));
            //附属设备
            tabsWrapper.Add(RequestWrapper.Instance().LoadSettingXmlString(@"
            <settings>
                <table>b_Sbda_Fssb</table>
                <where>
                    <field name='Fssb_Sbbh' cp='equal'></field>
                    <field name='Fssb_Fssbbh' cp='equal'></field>
                </where>
            </settings>"));
            var result = new b_SbdaService().EditPage(data, formWrapper, tabsWrapper);
        }
        //审核
        [System.Web.Http.HttpPost]
        public void Audit(string id, JObject data)
        {
            var status = data["status"].ToString();
            var comment = data["comment"].ToString();
            var result = new DevService().Audit(typeof(b_Sbda).Name, "Sbda_Sbbm", id, status, comment);
            DevHelper.ThrowHttpExceptionWhen(result < 0, "单据审核失败[Sbda_Sbbm={0}]，请重试或联系管理员！", id);
        }
        /// <summary>
        /// 删除主表（删除主表前是删除明细)
        /// </summary>
        /// <param name="id"></param>
        public void Delete(string id)
        {
            //判读该设备是否已经被使用
            //1、维修记录
            if (new b_WxjlService().GetModelList(new ParamQuery().AndWhere("Wxjl_Sbbh", id)).Count > 0)
            {
                DevHelper.ThrowHttpExceptionWhen(true, "删除设备档案分类失败[Wxjl_Sbbh={0}]，该类型已经被维修记录使用！", id);
            }
            //2、保养计划 
            if (new b_ByjhService().GetModelList(new ParamQuery().AndWhere("Byjh_Sbbh", id)).Count > 0)
            {
                DevHelper.ThrowHttpExceptionWhen(true, "删除设备档案分类失败[Byjh_Sbbh={0}]，该类型已经被保养计划使用！", id);
            }

            //开始执行删除操作
            var result = new b_SbdaService().Delete(ParamDelete.Instance().AndWhere("Sbda_Sbbm", id));
            DevHelper.ThrowHttpExceptionWhen(result <= 0, "单据删除失败[Sbda_Sbbm={0}]，请重试或联系管理员！", id);
        }

        #region 设备类别
        /// <summary>
        /// 设备类别-查询 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public dynamic GetTypes(RequestWrapper request)
        {
            request.LoadSettingXmlString(@"
            <settings defaultOrderBy='Sblbzd_Lbbh'>
               <where defaultIgnoreEmpty='true'>
                    <field name='Sblbzd_Lbbh'  cp='equal'></field>
                    <field name='Sblbzd_Lbmc'  cp='like' ></field>
                </where>
            </settings>
            ");
            var result = new b_SblbzdService().GetDynamicList(request.ToParamQuery());
            return result;
        }

        /// <summary>
        /// 设备类别-编辑
        /// </summary>
        /// <param name="data"></param>
        [System.Web.Http.HttpPost]
        public void EditType(dynamic data)
        {
            var listWrapper = RequestWrapper.Instance().LoadSettingXmlString(@"
            <settings>
                <table>b_Sblbzd</table>
                <where>
                    <field name='Sblbzd_Lbbh' cp='equal'></field>
                </where>
            </settings>");
            var service = new b_SblbzdService();
            var result = service.Edit(null, listWrapper, data);
        }

        /// <summary>
        /// 删除设备档案类别
        /// </summary>
        /// <param name="id"></param>
        public void DeleteTypeCode(string id)
        {
            //判断是否已经使用 2014-12-09
            if (new b_SbdaService().GetModelList(new ParamQuery().AndWhere("Sbda_lbbh", id)).Count > 0)
            {
                DevHelper.ThrowHttpExceptionWhen(true, "删除设备档案分类失败[Sbda_lbbh={0}]，该文件类型已经被使用！", id);
            }
            var result = new b_SblbzdService().Delete(ParamDelete.Instance().AndWhere("Sblbzd_Lbbh", id));
            DevHelper.ThrowHttpExceptionWhen(result <= 0, "删除设备档案分类失败[Sblbzd_Lbbh={0}]，请重试或联系管理员！", id);
        }


        #endregion



    }

}
